﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;

namespace FilesMerge
{
    public partial class Main : Form
    {
        System.Threading.Thread taskThread = null;
        Timer timingTime = null;

        private string srcFolder = string.Empty;
        private string dstFile = string.Empty;
        private string[] stuffixs = null;
        private int timeSeconds = 0;
        private int hour = 0;
        private int minute = 0;
        private int seconds = 0;
        private bool isMerge = false;
        private bool isWriteFileName = false;

        public Main()
        {
            InitializeComponent();
            btnStop.Enabled = false;
            InitCmbSuffixList();
            taskThread = new System.Threading.Thread(new System.Threading.ThreadStart(Search));
            Files.Singleton.ProcessMergeChangedHandler = new MergeProcessChanged(ProcessChangedHandler);
            timingTime = new Timer();
            timingTime.Interval = 1000;
            timingTime.Tick += timingTime_Tick;
        }

        void timingTime_Tick(object sender, EventArgs e)
        {
            ++timeSeconds;
            if(timeSeconds>3600)
            {
                hour = timeSeconds / 3600;
            }
            if(timeSeconds>60)
            {
                minute = (timeSeconds - hour * 3600) / 60;
            }
            seconds = (timeSeconds - hour * 3600) % 60;

            toollabelTime.Text = string.Format("耗时:{0}时{1}分{2}秒", hour, minute, seconds);
        }

        private void InitCmbSuffixList()
        {
            cmbFileSuffix.Items.AddRange(new object[] { 
             "*.cs",
             "*.txt",
             "*.txt,*.html",
             "*.*"
            });

            cmbFileSuffix.SelectedIndex = 0;
        }

        private void Search()
        {
            try
            {
                isMerge = true;
                SearchAndMergeFiles(srcFolder, dstFile, stuffixs);
                isMerge = false;
            }
            catch
            { }
            BeginInvoke(new MethodInvoker(() =>
            {
                timingTime.Stop();
                timeSeconds = 0;
                toollabelReady.Text = "执行完成!";
                operatePanel.Enabled = true;
                btnMerge.Enabled = true;
                btnStop.Enabled = false;
            }));
        }

        private bool SearchAndMergeFiles(string srcFolder,string dstFile,string[] searchParttens)
        {
            List<string> folderFiles = new List<string>(32);

            Files.Singleton.GetFolderFiles(srcFolder, searchParttens, ref folderFiles);

            BeginInvoke(new MethodInvoker(() =>
            {
                toollabelFileCount.Text = string.Format("文件数:{0}", folderFiles.Count);
                toollabelProcessbar.Maximum = folderFiles.Count;
            }));

            if (folderFiles.Count > 0)
            {
                return Files.Singleton.WriteMergeFiles(folderFiles, dstFile, isWriteFileName);
            }
            return false;
        }

        private void ProcessChangedHandler(int count,float percantage)
        {
            try
            {
                BeginInvoke(new MethodInvoker(() =>
                {
                    if (count <= toollabelProcessbar.Maximum)
                    {
                        toollabelProcessbar.Value = count;
                        toollabelPercantage.Text = string.Format("[{0}]{1}%", count, percantage);
                    }
                }));
            }catch
            { }
        }

        private void btnMerge_Click(object sender, EventArgs e)
        {
            try
            {
                stuffixs = cmbFileSuffix.Text.Trim().Split(new string[] { "," }, StringSplitOptions.RemoveEmptyEntries);

                if (stuffixs.Length == 0) stuffixs = new string[] { "*.*" };

                srcFolder = tbSourceFolder.Text.Trim();
                dstFile = tbTargetFile.Text.Trim();

                if (srcFolder.Length <= 0 || !Files.Singleton.IsExistFolder(srcFolder))
                {
                    MessageBox.Show("源文件夹不存在...", "提示");
                    return;
                }
                if (dstFile.Length <= 0)
                {
                    MessageBox.Show("目标文件不能为空", "提示");
                    return;
                }
                if (Files.Singleton.IsExistFile(dstFile))
                {
                    if (MessageBox.Show("文件已经存在,是否覆盖?", "提示", MessageBoxButtons.YesNo) != DialogResult.Yes) return;
                }

                operatePanel.Enabled = false;
                btnMerge.Enabled = false;
                btnStop.Enabled = true;
                toollabelReady.Text = "正在执行,请稍候...";
                if (taskThread.ThreadState != System.Threading.ThreadState.Unstarted)
                {
                    if (taskThread.ThreadState != System.Threading.ThreadState.Stopped)
                    {
                        taskThread.Interrupt();
                        taskThread.Abort();
                        taskThread.DisableComObjectEagerCleanup();
                    }
                }
                taskThread = new System.Threading.Thread(new System.Threading.ThreadStart(Search));
                taskThread.Start();
                timingTime.Start();
            }
            catch
            { }
        }

        private void btnOpenFolder_Click(object sender, EventArgs e)
        {
            FolderBrowserDialog open = new FolderBrowserDialog();
            if(open.ShowDialog()==DialogResult.OK)
            {
                tbSourceFolder.Text = open.SelectedPath.Trim();
                string path = Application.StartupPath;
                string disk = path.Substring(0, 2);
                tbTargetFile.Text = string.Format("{0}\\MergeFile-{1}.txt", disk, DateTime.Now.ToString("yyMMddHHmm"));
            }
        }

        private void btnOpenDstFolder(object sender, EventArgs e)
        {
            try
            {
                string dstPath = tbTargetFile.Text.Trim();
                if (dstPath.Length > 0 && Files.Singleton.IsExistFolder(dstPath))
                {
                    string dir = System.IO.Path.GetDirectoryName(dstPath);
                    System.Diagnostics.Process.Start(dir);
                }
            }
            catch
            { }
        }

        private void btnStop_Click(object sender, EventArgs e)
        {
            try
            {
                if (isMerge)
                {
                    taskThread.Interrupt();
                    taskThread.Abort();
                    taskThread.DisableComObjectEagerCleanup();
                }
            }
            catch
            { }
        }

        private void ckbWriteFileName_CheckedChanged(object sender, EventArgs e)
        {
            isWriteFileName = ckbWriteFileName.Checked;
        }
    }
}
